import mido
import json
from typing import *

channel0, channel1 = None, None
with open("/storage/emulated/0/mymidi/myTongJi.txt") as f:
    notes = [json.loads(note.replace("'", '"')) for note in f.read().split(",\n")]
    channel0 = [note for note in notes if note["channel"] == 0]
    channel1 = [note for note in notes if note["channel"] == 1]


def merge_channel(channel0, channel1) -> list:
    for i in range(1, len(channel0)):
        channel0[i]["time"] += channel0[i - 1]["time"]
    for i in range(1, len(channel1)):
        channel1[i]["time"] += channel1[i - 1]["time"]

    notes = sorted(channel0 + channel1, key=lambda x: x["time"])

    i = len(notes) - 1
    while i > 0:
        notes[i]["time"] -= notes[i - 1]["time"]
        notes[i]["channel"] = 0

        i -= 1

    return notes


mid = mido.MidiFile()
track = mido.MidiTrack()
mid.tracks.append(track)
# track.append(mido.Message("program_change", program=56))

with open("/storage/emulated/0/mymidi/myTongJi-mergeChannel.txt", "w") as f:
    # print(merge_channel(channel0, channel1))
    for note in merge_channel(channel0, channel1):
        f.write(str(note) + "\n")
        track.append(mido.Message(**note))

    mid.save("/storage/emulated/0/mymidi/myTongJi-mergeChannel.mid")
